package main

import (
	"flag"
	"fmt"
	"net/url"
	"os"
	"os/signal"
	"time"

	"github.com/gorilla/websocket"
)

var addr = flag.String("addr", "localhost:8080", "http service address")
var count = flag.Int("count", 1, "client count")
var interval = flag.Int("interval", 1000, "client send pack time interval")

type Client struct {
	conn *websocket.Conn
}

func (this *Client) run() {
	go this.reader()

	ticker := time.NewTicker(time.Duration(*interval) * time.Millisecond)
	defer ticker.Stop()
	for {
		select {
		case t := <-ticker.C:
			fmt.Println("send: ", t.String())
			err := this.conn.WriteMessage(websocket.TextMessage, []byte(t.String()+"\n"))
			if err != nil {
				fmt.Println("write:", err)
				return
			}
		}
	}
}

func (this *Client) reader() {
	defer this.close()
	for {
		_, message, err := this.conn.ReadMessage()
		if err != nil {
			fmt.Println("read:", err)
			return
		}
		fmt.Printf("recv: %s", message)
	}
}

func (this *Client) close() {
	this.conn.Close()
}

func main() {
	flag.Parse()

	for i := 0; i < *count; i++ {
		go func() {
			u := url.URL{Scheme: "ws", Host: *addr, Path: "/"}
			fmt.Printf("id:%d connecting to %s\n", i, u.String())
			c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
			if err != nil {
				fmt.Printf("dial:", err)
				return
			}
			fmt.Printf("id:%d run\n", i)
			client := &Client{conn: c}
			client.run()
		}()
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, os.Kill)
	<-c
}
